
<?php

$cmd=$_REQUEST['cmd'];
switch($cmd)
{
    case 1:
        search_departments();
        break;
    case 2:
        addDepartment();
        break;
        
    case 3:
        getDepartments();
        break;
    case 4:
        updateDpartment();
        break;
    case 5:
        deleteDepartment();
        break;
}

function search_departments(){
    if(isset($_REQUEST['st'])){
        include_once('department.php');
        $obj1 = new departments();

        $search_text = $_REQUEST['st'];

        if($obj1->search_department($search_text)){
            $row=$obj1->fetch();
            echo '{"result":1,"departments":[';	//start of json object
            while($row){
                    echo json_encode($row);	//convert the result array to json object
                    $row=$obj1->fetch();
                    if($row){
                            echo ",";					//if there are more rows, add comma 
                    }
            }
            echo "]}";
        }else{
            //return error
            echo '{"result":0,"message": "search did not work."}';
            return;
        } 
    }
            
}

function addDepartment(){
    if(isset($_REQUEST['dn'])){
            include_once 'department.php';
            
            $name = $_REQUEST['dn'];
            $obj = new departments();
            if(!$obj->add_department($name)){
                 echo '{"result":0,"message": "add did not work."}';
            }
            else{
      
             echo '{"result":1,"message": "Department Added"}';
            }
                
        }
}

function getDepartments(){
    include_once('department.php');
        $obj1 = new departments();
        $obj1->get_all_departments();
        
        $row=$obj1->fetch();
        echo '{"result":1,"departments":[';	//start of json object
        while($row){
                echo json_encode($row);			//convert the result array to json object
                $row=$obj1->fetch();
                if($row){
                        echo ",";					//if there are more rows, add comma 
                }
        }
        echo "]}";
}

function updateDpartment(){
   if(isset($_REQUEST['dn']) && isset($_REQUEST['did'])){
        include_once("department.php");

        $dn = $_REQUEST['dn'];
        $did = $_REQUEST['did'];

        $obj = new departments();
        if(!$obj->edit_department($dn, $did)){
            echo '{"result":0,"message": "update did not work."}';
        }
        else{
            echo '{"result":1,"message": "update successful"}';
        }

    } 
}

function deleteDepartment(){
    include_once 'department.php';
    if(isset( $_REQUEST["id"])){
        $did = intval($_REQUEST['id']);

        $obj = new departments();
        if(!$obj->delete_department($did)){
            echo '{"result":0,"message": "delete did not work."}';
        }
        else {
            echo '{"result":1,"message": "department deleted "}';
        }
    }
}
?>
